﻿using System;
using System.IO;
using System.Text;
using CodeGeneration.Util;
using NVelocity;
using NVelocity.App;
using NVelocity.Runtime;

namespace CodeGeneration.TextEngine
{
    public class NVelocityTextEngine:ITextEngine
    {
        private readonly VelocityEngine _velocityEngine;

        public NVelocityTextEngine()
        {
            _velocityEngine = new VelocityEngine();
            _velocityEngine.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file");
            _velocityEngine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, Path.Combine(Environment.CurrentDirectory, "Template\\NVelocity"));
            _velocityEngine.SetProperty(RuntimeConstants.INPUT_ENCODING,"utf-8");
            _velocityEngine.SetProperty(RuntimeConstants.OUTPUT_ENCODING, "utf-8");
            _velocityEngine.Init();
        }
        public void TransferText<T>(T model, string file)
        {
            var name = typeof(T).Name.ToLower();
            name = name.Substring(0, name.LastIndexOf("model", StringComparison.Ordinal));
            var vltContext = new VelocityContext();
            vltContext.Put("model", model);//添加数据，在模板中可以通过$dataName来引用数据　
            var vltTemplate = _velocityEngine.GetTemplate($"{name}.nvelocity");//设定模板
            var vltWriter = new StringWriter();
            vltTemplate.Merge(vltContext, vltWriter);
            string result = vltWriter.GetStringBuilder().ToString();
            TemplateUtil.RenderStringToFile(result, file);
        }
    }
}